package com.yulp.springboot2task.utils;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @description:
 * @date: 2019/11/4 10:19.
 * @author: yulipeng.
 */
public class JedisPoolUtils {
    private static JedisPool pool;

    static {
        //加载配置文件
        InputStream in = JedisPoolUtils.class.getClassLoader().getResourceAsStream("redis.properties");
        Properties pro = new Properties();
        try {
            pro.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获得池子对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(Integer.parseInt(pro.get("redis.maxIdle").toString()));//最大闲置个数
        poolConfig.setMinIdle(Integer.parseInt(pro.get("redis.minIdle").toString()));//最小闲置个数
        poolConfig.setMaxTotal(Integer.parseInt(pro.get("redis.maxTotal").toString()));//最大连接数
        //pool = new JedisPool(poolConfig, pro.getProperty("redis.url"), Integer.parseInt(pro.get("redis.port").toString()));
        pool = new JedisPool(poolConfig, pro.getProperty("redis.url"),
                Integer.parseInt(pro.get("redis.port").toString()), 1000,
                pro.get("redis.password").toString());
    }

    //获得jedis资源的方法
    public static Jedis getJedis() {
        return pool.getResource();
    }

    //存值：
    public static void setPool(String key,String value){
        getJedis().set(key,value);
    }

    public static void setPool(String key,String value, int expireSeconds){
        getJedis().set(key,value);
        getJedis().expire(key, expireSeconds);
    }

    //取值：
    public static String getPool(String key){
        return getJedis().get(key);
    }

    public static void main(String[] args) {
        setPool("key","value", 10);
        System.out.println(getPool("key"));
    }
}